package com.ptit.piclient.tools;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
//import android.util.Log;

import android.util.Log;

import com.ptit.piclient.model.*;

public class PiConnector {
	private ArrayList<Song> allSong = null;
	public ArrayList<Song> getAllSong(){		
		return allSong;
	}
	//----
	/**
	 * @param args
	 */
	//private URL url = null;
	//private HttpURLConnection urlConnection = null;
	private static PiConnector instance = null;
	private String piURL = "http://192.168.1.8:8082";
	private PiConnector() {
		allSong = getAllSongFromPi();
	}

	public static PiConnector getInstance() {
		if (instance == null)
			instance = new PiConnector();
		return instance;
	}
	
	private ArrayList<Song> getAllSongFromPi(){
		URL url = null;
		HttpURLConnection urlConnection = null;
		DataOutputStream das = null;
		ArrayList<Song> songlist = new ArrayList<Song>();		
		try{
			
		url = new URL(piURL +"/jsonrpc");
		urlConnection = (HttpURLConnection) url.openConnection();
		urlConnection.setRequestMethod("POST");
		urlConnection.setRequestProperty("Content-Type",
				"application/json; charset=utf-8");
		urlConnection.setRequestProperty("Content-Language", "vi-VN");
		urlConnection.setUseCaches(false);
		urlConnection.setDoInput(true);
		urlConnection.setDoOutput(true);

//		Log.i("temp","^^");
		try{
			das = new DataOutputStream(urlConnection.getOutputStream());
		}catch(Exception ex){
			ex.printStackTrace();
			Log.i("bttt", " "+ex.toString());
		}		
		
		StringBuffer response = new StringBuffer();		
		
		das.writeBytes("{\"jsonrpc\": \"2.0\", \"method\": \"AudioLibrary.GetSongs\","
				+ " \"params\": { \"limits\": { \"start\" : 0 }, \"properties\": [ \"artist\", \"duration\", \"album\", \"track\" ], \"sort\": { \"order\": \"ascending\", \"method\": \"track\", \"ignorearticle\": true } }, \"id\": \"getsongs\"}");

		das.flush();
		das.close();

		InputStream is = urlConnection.getInputStream();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		String line = "";
		Log.i("input-stream","ok");
		while ((line = rd.readLine()) != null) {
			response.append(line);
			response.append('\r');
		}
		rd.close();
		is.close();		
		JSONObject jO = new JSONObject(response.toString());
		JSONObject result = jO.optJSONObject("result");
		JSONArray array = result.optJSONArray("songs");
		JSONObject t = new JSONObject();
		
		for (int i = 0; i < array.length(); i++) {
			t = array.getJSONObject(i);
			Song s = new Song();
			s.setSongid(t.optInt("songid"));
			s.setAlbum(t.optString("album"));
			s.setDuration(t.optInt("duration"));
			s.setName(t.optString("label"));
			//ArrayList<String> artistList = new ArrayList<String>();
			JSONArray artistJSON = t.optJSONArray("artist");
			String [] artist = new String[artistJSON.length()];
			for(int j  =0; j < artistJSON.length(); j++) {
				artist[j] = artistJSON.optString(j);
			}
			s.setArtist(artist);
			songlist.add(s);
		}
		
		//Close them
		
		urlConnection.disconnect();
		}catch(Exception ex){
			String err = (ex.getMessage()==null)?"getsonglist":ex.getMessage();
			Log.e("getsonglist",err);
		}
		return songlist;
	}

	public void playsong(int i) {
		URL url = null;
		HttpURLConnection urlConnection = null;
		DataOutputStream das = null;
		try{
		url = new URL(piURL + "/jsonrpc");
		urlConnection = (HttpURLConnection) url.openConnection();
		urlConnection.setRequestMethod("POST");
		urlConnection.setRequestProperty("Content-Type",
				"application/json; charset=utf-8");
		urlConnection.setRequestProperty("Content-Language", "vi-VN");
		urlConnection.setUseCaches(false);
		urlConnection.setDoInput(true);
		urlConnection.setDoOutput(true);
		Log.i("step1","OK");
		das = new DataOutputStream(urlConnection.getOutputStream());
		//das.writeBytes("{\"jsonrpc\": \"2.0\", \"method\": \"Player.Open\","
			//	+ " \"id\": 1, \"params\":\"{\"item\":{\"playlistid\": 0} }\"}");
		das.writeBytes("{\"jsonrpc\": \"2.0\", \"id\" : \"playsong\", "
                + "\"method\": \"Player.Open\","
                 + "\"params\":{\"item\": {\"position\":"+i +",\"playlistid\":0}}}");			
		Log.i("step2","OK");
		StringBuffer response = new StringBuffer();
		InputStream is = urlConnection.getInputStream();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		String line = "";
		Log.i("step3","OK");
		while ((line = rd.readLine()) != null) {
			response.append(line);
			response.append('\r');
		}
		rd.close();
		is.close();
		Log.i("step4","OK");
		Log.e("opensong",response.toString());
		das.close();
		urlConnection.disconnect();		
		}catch(Exception ex){
			String err = (ex.getMessage()==null)?"true":ex.getMessage();
			Log.e("openningsongerror",err);
		}
	}

	/**
	 * Add songs to playlist
	 */
	public void addToPlaylist(ArrayList<Song> songlist){
		StringBuffer batch = new StringBuffer();
		batch.append("[");
		Song s ;
		int size = 10;//songlist.size();
		for(int i = 0; i < size - 1; i++){
			s = songlist.get(i);
			batch.append("{ \"jsonrpc\" : \"2.0\", \"method\" : \"Playlist.Add\", \"params\" : { \"item\" : { \"songid\" : "
			+s.getSongid() +" }, \"playlistid\" : 0 } },");			
		}
		s = songlist.get(size - 1);
		batch .append("{  \"jsonrpc\" : \"2.0\", \"method\" : \"Playlist.Add\", \"params\" : { \"item\" : { \"songid\" : "+s.getSongid()+" }, \"playlistid\" : 0 } }");
		batch.append("]");
		
		//Connect and request
		URL url = null;
		HttpURLConnection urlConnection = null;
		DataOutputStream das = null;
		try {
			url = new URL(piURL + "/jsonrpc");
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("POST");
			urlConnection.setRequestProperty("Content-Type",
					"application/json; charset=utf-8");
			urlConnection.setRequestProperty("Content-Language", "vi-VN");
			urlConnection.setUseCaches(false);
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(true);
			das = new DataOutputStream(urlConnection.getOutputStream());		
			Log.e("batchAdd","before sending...");
			das.writeBytes(batch.toString());
			
			StringBuffer response = new StringBuffer();
			InputStream is = urlConnection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line = "";

			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			rd.close();
			is.close();
			
			Log.e("batchAdd",batch.toString());
			Log.e("responeofbatch","AAA" + response.toString());
			das.close();
			urlConnection.disconnect();
		} catch (Exception ex) {
			String err = (ex.getMessage()==null)?"True":ex.getMessage();
			Log.e("exceptionBatchAddToPlaylist:",err);			
		}
		
		//Close
	}
	/**
	 * Get infor of current playing
	 * @return
	 */
	public Song getCurrentItem() {
		// TODO Auto-generated method stub
		URL url = null;
		HttpURLConnection urlConnection = null;
		DataOutputStream das = null;
		try {
			url = new URL(piURL + "/jsonrpc");
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("POST");
			urlConnection.setRequestProperty("Content-Type",
					"application/json; charset=utf-8");
			urlConnection.setRequestProperty("Content-Language", "vi-VN");
			urlConnection.setUseCaches(false);
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(true);
			das = new DataOutputStream(urlConnection.getOutputStream());
			das.writeBytes("");			
			StringBuffer response = new StringBuffer();
			InputStream is = urlConnection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line = "";

			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			rd.close();
			is.close();
			
			Log.e("getcurrentSong",response.toString());
			das.close();
			urlConnection.disconnect();
		} catch (Exception e) {
			String s2 = e.getMessage(); // s2 == null !!!!!!!
      		if(s2 != null)
      		 Log.e("getcurrentsong", e.getMessage());
      		else 
      		 Log.e("getcurrentsong", "Bi loi khi get currentsong");
			
		}
		return null;
	}
}
